import CryptoJS from 'crypto-js';

/**
 * 随机生成16位的AES密钥
 * @returns {string}
 */
export const getAESKey = () => {
    var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    var n = 16;
    var res = "";
    for (var i = 0; i < n; i++) {
        var id = Math.ceil(Math.random() * 35);
        res += chars[id];
    }
    return res;
}

/**
 * 加密
 * @param data
 * @param aesKey
 * @returns {string}
 * @constructor
 */
export const encryptAes = (data, aesKey) => {
    let key = CryptoJS.enc.Utf8.parse(aesKey);
    let srcs = CryptoJS.enc.Utf8.parse(data);
    let encrypted = CryptoJS.AES.encrypt(srcs, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    console.log(encrypted.ciphertext)
    return encrypted.ciphertext.toString();
};

/**
 * 解密Aes
 * @param data
 * @param aesKey
 * @returns {string}
 */
export const decryptAes = (data, aesKey) => {
    let keyStr = aesKey ? aesKey : "1234567890abcdef";
    var key = CryptoJS.enc.Utf8.parse(keyStr);
    var decrypt = CryptoJS.AES.decrypt(data, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
};
